package com.shengchang.hu.supervision.UI;

import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import android.os.Parcelable;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.MainActivity;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.LoginBar;
import com.shengchang.hu.supervision.Utils.AlertDialog;
import com.shengchang.hu.supervision.Utils.Contants;
import com.shengchang.hu.supervision.Utils.StringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Locale;

import NFC.NdefMessageParser;
import NFC.ParsedNdefRecord;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends BaseActivity implements View.OnClickListener{



    LoginBar loginbar;
    EditText etUsername;
    EditText etPwd;
    Button btnLogin;
    CheckBox cbRememberLogin;
    private AlertDialog alertDialog;
    SharedPreferences sp = null;
    LinearLayout loginLine;
    EditText scanUsername;
    Button scanBtnLogin;

    LinearLayout sacnLine;
    private long mPressedBackTime;
    private static final DateFormat TIME_FORMAT = SimpleDateFormat
            .getDateTimeInstance();
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private NdefMessage mNdefPushMessage;
    private android.app.AlertDialog mDialog;
    private final static String LOGIN_API = Contants.LOGIN_API;
    private  final  static  String READ_LOGIN_API=Contants.READ_LOGIN_API;
    OkHttpClient okHttpClient = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        InitAlert();
        resolveIntent(getIntent());
        mDialog = new android.app.AlertDialog.Builder(this).setNeutralButton("Ok", null)
                .create();

        // 获取默认的NFC控制器
        mAdapter = NfcAdapter.getDefaultAdapter(this);

        //拦截系统级的NFC扫描，例如扫描蓝牙
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord("",
                Locale.ENGLISH, true) });
        if ((!StringUtil.isEmpty(App.getApp().getToken()))) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mAdapter == null) {
            if (!mAdapter.isEnabled()) {
                showWirelessSettingsDialog();
            }

            showMessage("error", " NO NFC");
            showShortToast("设备不支持NFC");


            return;
        }
        if (!mAdapter.isEnabled()) {
            showShortToast("请在系统设置中先启用NFC功能");

            return;
        }

        if (mAdapter != null) {
            //隐式启动
            mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            mAdapter.enableForegroundNdefPush(this, mNdefPushMessage);
        }
    }

    private void initView() {
        loginbar=findViewById(R.id.loginbar);
        etUsername=findViewById(R.id.et_username);
        etPwd=findViewById(R.id.et_pwd);
        btnLogin=findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        cbRememberLogin=findViewById(R.id.cb_remember_login);
        loginLine=findViewById(R.id.login_line);
        scanUsername=findViewById(R.id.scan_username);
        scanBtnLogin=findViewById(R.id.scan_btn_login);
        scanBtnLogin.setOnClickListener(this);
        sacnLine=findViewById(R.id.sacn_line);
        loginbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        cbRememberLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (cbRememberLogin.isChecked()) {

                    sp.edit().putBoolean("IsCheck", true).commit();
                } else {

                    sp.edit().putBoolean("IsCheck", false).commit();
                }
            }
        });
        sp = this.getSharedPreferences("info", Context.MODE_PRIVATE);
        if (sp.getBoolean("IsCheck", true)) {
            //设置默认是记录密码状态
            cbRememberLogin.setChecked(true);
            etUsername.setText(sp.getString("UserName", ""));
            etPwd.setText(sp.getString("Password", ""));
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if (TextUtils.isEmpty(etUsername.getText().toString())) {
                    showShortToast("用户名不能为空");
                } else if (TextUtils.isEmpty(etPwd.getText().toString())) {
                    showShortToast("密码不能为空");
                } else {
                    showProgressDialog();
                    LoginRequest();
                }

                if (cbRememberLogin.isChecked()) {
                    //记住用户名、密码、
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("UserName", etUsername.getText().toString());
                    editor.putString("Password", etPwd.getText().toString());
                    editor.commit();
                } else {
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("UserName", null);
                    editor.putString("Password", null);
                    editor.putBoolean("auto", false);
                    editor.commit();
                }

                break;

            case R.id.scan_btn_login:
               if (!TextUtils.isEmpty(scanUsername.getText().toString())&&!TextUtils.isEmpty(App.getApp().getToken())){
                   Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
                   startActivity(mIntent);
                   finish();
            }
                break;
        }
    }

    private void LoginRequest() {
        RequestBody formBody = new FormBody.Builder()
                .add("loginname", etUsername.getText().toString())
                .add("password", etPwd.getText().toString())
                .build();
        Request request = new Request.Builder()
                .url(LOGIN_API)
                .post(formBody)
                .build();
        Log.d("sdeujcia", LOGIN_API + "?loginname=" + etUsername.getText().toString() + "&password=" + etPwd.getText().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String loginstr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoginResPonse(loginstr);
                    }
                });

            }
        });

    }

    private void LoginResPonse(String loginstr) {
        try {
            JSONObject loginJson = new JSONObject(loginstr);
            String loginMsg = loginJson.getString("message");
            if (loginMsg.equals(Contants.Wrong_account)) {
                dismissProgressDialog();
                showLongToast("请求失败");
            } else if (loginMsg.equals(Contants.Abnormal_occurrence)) {
                dismissProgressDialog();
                showLongToast("请求异常，请检查网络");
            } else if (loginMsg.equals(Contants.Successful_operation)) {
                dismissProgressDialog();
                Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(mIntent);
                finish();
            } else if (loginMsg.equals(Contants.Jurisdiction)) {
                dismissProgressDialog();
                showShortToast("服务器出错，请联系厂商");
            } else if (loginMsg.equals(Contants.Jurisd)) {
                dismissProgressDialog();
                showShortToast("账号出错");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject DataJson = new JSONObject(loginstr);
            JSONObject TokenJson = DataJson.getJSONObject("loginUser");
            App.getApp().setToken(TokenJson.getString("id"));
            String name = TokenJson.getString("name");
            App.getApp().setName(name);
            Log.d("jdkeis", App.getApp().getName());


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void InitAlert() {
        alertDialog = new AlertDialog(LoginActivity.this,
                "提示", "请选择登录方式", "刷卡登录", "用户名登录",
                new AlertDialog.OnDialogButtonClickListener() {
                    @Override
                    public void onDialogButtonClick(boolean isPositive) {
                        if (isPositive) {

                        } else {
                            sacnLine.setVisibility(View.GONE);
                            loginLine.setVisibility(View.VISIBLE);
                        }
                    }
                });
        if (!LoginActivity.this.isFinishing()) {
            alertDialog.show();
        }


    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAdapter != null) {
            //隐式启动
            mAdapter.disableForegroundDispatch(this);
            mAdapter.disableForegroundNdefPush(this);
        }
    }

    private void showMessage(String title, String message) {
        mDialog.setTitle(title);
        mDialog.setMessage(message);
        mDialog.show();
    }

    private NdefRecord newTextRecord(String text, Locale locale,
                                     boolean encodeInUtf8) {
        byte[] langBytes = locale.getLanguage().getBytes(
                Charset.forName("US-ASCII"));

        Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset
                .forName("UTF-16");
        byte[] textBytes = text.getBytes(utfEncoding);

        int utfBit = encodeInUtf8 ? 0 : (1 << 7);
        char status = (char) (utfBit + langBytes.length);

        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        data[0] = (byte) status;
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
                textBytes.length);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                new byte[0], data);
    }

    private void showWirelessSettingsDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setMessage("nfc_disabled");
        builder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(
                                Settings.ACTION_WIRELESS_SETTINGS);
                        startActivity(intent);
                    }
                });
        builder.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        builder.create().show();
        return;
    }

    //初步判断是什么类型NFC卡
    private void resolveIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Parcelable tag = intent
                        .getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
                        empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
            }
            // Setup the views

//        showShortToast("");
            buildTagViews(msgs);
        }
    }

    //一般公家卡，扫描的信息
    private String dumpTagData(Parcelable p) {
        StringBuilder sb = new StringBuilder();
        Tag tag = (Tag) p;
        byte[] id = tag.getId();
        sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
        sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
        sb.append("ID (reversed): ").append(getReversed(id)).append("\n");

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('\n');
                MifareClassic mifareTag = MifareClassic.get(tag);
                String type = "Unknown";
                switch (mifareTag.getType()) {
                    case MifareClassic.TYPE_CLASSIC:
                        type = "Classic";
                        break;
                    case MifareClassic.TYPE_PLUS:
                        type = "Plus";
                        break;
                    case MifareClassic.TYPE_PRO:
                        type = "Pro";
                        break;
                }
                sb.append("Mifare Classic type: ");
                sb.append(type);
                sb.append('\n');

                sb.append("Mifare size: ");
                sb.append(mifareTag.getSize() + " bytes");
                sb.append('\n');

                sb.append("Mifare sectors: ");
                sb.append(mifareTag.getSectorCount());
                sb.append('\n');

                sb.append("Mifare blocks: ");
                sb.append(mifareTag.getBlockCount());
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('\n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }

        return sb.toString();
    }

    private String getHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private long getReversed(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = bytes.length - 1; i >= 0; --i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    //显示NFC扫描的数据
    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) {
            return;
        }
        Date now = new Date();
        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
        final int size = records.size();
        for (int i = 0; i < size; i++) {
            TextView timeView = new TextView(this);
            timeView.setText(TIME_FORMAT.format(now));
            ParsedNdefRecord record = records.get(i);

//            showShortToast(String.valueOf(record.getViewText()));
            String viewText = record.getViewText();
            String[] split = viewText.split("\\n");
            String[] split2 = split[1].split(" ");
            final String string = split2[3];
            Log.d("jdeuidia", string);
            if (!TextUtils.isEmpty(string) &&  string.length()>9){
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    showProgressDialog();
                                    ReadLoginRequest(string);


                                }
                            });
                        } catch (InputMismatchException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
//               showShortToast(string);
//               Log.d("record", String.valueOf(record.getViewText()));
            }else  if (!TextUtils.isEmpty(string) &&  string.length()<=9){
                final   String  s="0"+string;

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    showProgressDialog();
                                    ReadLoginRequest(s);


                                }
                            });
                        } catch (InputMismatchException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }else{
                showShortToast("读卡失败");
            }

        }
    }
    private void ReadLoginRequest(String result) {
        RequestBody formBody = new FormBody.Builder()
                .add("cardCode",result.replaceAll(" ",""))
                .build();
        Request request = new Request.Builder()
                .url(READ_LOGIN_API)
                .post(formBody)
                .build();
        Log.d("READ_CARD_API",READ_LOGIN_API+"?cardCode="+result.toString().replaceAll(" ",""));
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }				});				//此处会发生异常//
                    }		}).start();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String  readcard=response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ReadLoginResPonse(readcard);
                    }
                });

            }
        });

    }

    private void ReadLoginResPonse(String readcard) {
        try {
            JSONObject loginJson=new JSONObject(readcard);
            String loginMsg=loginJson.getString("message");
            if (loginMsg.equals(Contants.Wrong_account)){
                dismissProgressDialog();
                showLongToast("请求失败");
            }else if (loginMsg.equals(Contants.Abnormal_occurrence)){
                dismissProgressDialog();
                showLongToast("请求异常，请检查网络");
            }else if (loginMsg.equals(Contants.Successful_operation)){
                dismissProgressDialog();

            }else if (loginMsg.equals(Contants.Jurisdiction)){
                dismissProgressDialog();
                showShortToast("服务器出错，请联系厂商");
            }else if (loginMsg.equals(Contants.Jurisd)){
                dismissProgressDialog();
                showShortToast("账号出错");
            }else if (loginMsg.equals("20009")){
                dismissProgressDialog();
                showShortToast("类型不符合");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {

            JSONObject jsonObject = new JSONObject(readcard);
            JSONObject loginUser = jsonObject.getJSONObject("loginUser");
            App.getApp().setToken(loginUser.getString("id"));
//            App.getApp().setToken();
            String name=loginUser.getString("name");
            App.getApp().setName(name);
            scanUsername.setText(name);
            Log.d("jdkeis",App.getApp().getName());


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //获取系统隐式启动的
    @Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        resolveIntent(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public static void startActivity(Context paramContext) {
        paramContext.startActivity(new Intent(paramContext, LoginActivity.class));
    }

    @Override
    public void onBackPressed() {
        long l = System.currentTimeMillis();
        if (l - this.mPressedBackTime > 3000L) {
            showLongToast("再次轻触返回键退出程序");
            this.mPressedBackTime = l;
            return;
        }
        finish();
    }


}
